package de.unistuttgart.iaas.interaction.mail.services;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.apache.log4j.Logger;
//import org.apache.log4j.PropertyConfigurator;

import java.io.IOException;
//import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

import de.unistuttgart.iaas.interaction.mail.ProcessMail;
import de.unistuttgart.iaas.interaction.mail.ReceiveMail;
import de.unistuttgart.iaas.interaction.mail.Register;
import de.unistuttgart.iaas.interaction.mail.SendMail;
//import de.unistuttgart.iaas.interaction.mail.util.LogCreator;
//import de.unistuttgart.iaas.interaction.mail.util.LoggingFileHandler;

/**
 * This class uses TimerTask to let four services run automatically after the server starts.
 * 1. ReceiveMail() service runs every 2 minutes.
 * 2. register() service runs every 3 minutes.
 * 3. sendMail() service runs every 5 minutes.
 * 4. ProcessMail() service runs every 5 minutes.
 * 
 * @author Lina Sun
 * @see java.util.TimerTask
 * 
 */
public class AutoRun extends HttpServlet 
{
	private static final int RECEIVE_PERIOD = 1*60*1000;
	private static final int REGISTER_PERIOD = 2*60*1000;
	private static final int PERIOD = 2*60*1000;


	public void init()
	{
			
		final String config = getServletConfig().getInitParameter("ConfigFile");
	
		
			Timer timer = new Timer(true);
			
			/**TimerTask for ReceiveMail()*/
			timer.schedule(new TimerTask()
			{
				public void run()
				{
					try
					{	
						/** */
						ReceiveMail.ReceiveMail(config);
	
					}catch(Exception e){}
				}
			},0,RECEIVE_PERIOD);
			
			/**TimerTask for register()*/
			timer.schedule(new TimerTask()
			{
				public void run()
				{
					try
					{					
						Register.register(config);
	
					}catch(Exception e){}
				}
			},0,REGISTER_PERIOD);
			
	
			/**TimerTask for sendMail()*/
			timer.schedule(new TimerTask()
			{
				public void run()
				{
					try
					{					
						SendMail.sendMail(config);
	
					}catch(Exception e){}
				}
			},0,PERIOD);
			
			/**TimerTask for ProcessMail()*/
			timer.schedule(new TimerTask()
			{
				public void run()
				{
					try
					{					
						ProcessMail.ProcessMail(config);
	
					}catch(Exception e){}
				}
			},0,PERIOD);
		}
	
	
	//Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
    }
    
    //Clean up resources
    public void destroy() 
    {
    }
}
